package com.itheima.qingcheng.aop;


import com.itheima.qingcheng.mapper.OperateLogMapper;
import com.itheima.qingcheng.pojo.OperateLog;
import com.itheima.qingcheng.utils.ThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Arrays;

/**
 * @author zhangzhen
 * @version 1.0
 * @date 2025/1/19 11:01
 */
@Slf4j
@Component
@Aspect
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Around("@annotation(com.itheima.qingcheng.anno.Log)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {
      //记录开始时间
        long startime = System.currentTimeMillis();
        //执行方法
        Object result = joinPoint.proceed();
        //当前时间
        long endtime = System.currentTimeMillis();
        long costTime=endtime-startime;
        //构建日志对象
        OperateLog operateLog = new OperateLog();
        operateLog.setOperateEmpId(1);
        operateLog.setOperateTime(LocalDateTime.now());
        operateLog.setClassName(joinPoint.getTarget().getClass().getName());
        operateLog.setMethodName(joinPoint.getSignature().getName());
        operateLog.setMethodParams(Arrays.toString(joinPoint.getArgs()));
        operateLog.setReturnValue(result.toString());
        operateLog.setCostTime(costTime);
        //插入日志
        operateLogMapper.insert(operateLog);
        return result;
    }
    // 示例方法，获取当前用户ID
    private int getCurrentUserId() {
        // 这里应该根据实际情况从认证信息中获取当前登录用户的ID
        return ThreadLocalUtils.get();
    }
}
